package handlers;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import database.Connect;

/**
 * Handles the Clients
 * 
 * @author Nils Berlijn & Henderikus Harms
 */	
public class ClientHandler implements Runnable
{
	private boolean running;
	private Socket socket;
	private PrintWriter output;

	/**
	 * Initialize the ClientHandler
	 * 
	 * @param socket
	 */
	public ClientHandler(Socket socket)
	{
		this.running = true;
		this.socket = socket;
		
		try 
		{
			output = new PrintWriter(socket.getOutputStream(), true);
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}
	
	/**
	 * Start selecting data from the Database
	 */	
	@Override
	public void run() 
	{
		while(running)
		{
			output.println(readData());
			running = false;
		}
	}
	
	/**
	 * Read data from the Database
	 * The Connect class will be used to get a connection with the Database
	 * 
	 * @return output The output with data from the Database for the Client
	 */
	private String readData()
	{
		Connect.open();
		
		int stnInput = 10100;
		
		String output = "";
		
		try 
		{
			Statement st = Connect.connection.createStatement();
			String sql = ("SELECT * FROM measurement WHERE stn =   "+ stnInput +  "");
			ResultSet rs = st.executeQuery(sql);
			
			while(rs.next())
			{
				int stn = rs.getInt("STN");
				String date = rs.getString("DATE");
				String time = rs.getString("TIME");
				double temp = rs.getDouble("TEMP");
				double dewp = rs.getDouble("DEWP");
				double stp = rs.getDouble("STP");
				double slp = rs.getDouble("SLP");
				double visib = rs.getDouble("VISIB");
				double wsp = rs.getDouble("WDSP");
				double prcp = rs.getDouble("PRCP");
				double sndp = rs.getDouble("SNDP");
				String frshtt = rs.getString("FRSHTT");
				double clds = rs.getDouble("CLDC");
				int winddir = rs.getInt("WNDDIR");
				
				output += "STN: " + stn;
				output += "DATE: " + date;
				output += "TIME: " + time;
				output += "TEMP: " + temp;
				output += "DEWP: " + dewp;
				output += "STP: " + stp;
				output += "SLP: " + slp;
				output += "VISIB: " + visib;
				output += "WSP: " + wsp;
				output += "PRCP: " + prcp;
				output += "SNDP: " + sndp;
				output += "FRSHTT: " + frshtt;
				output += "CLDS: " + clds;
				output += "WINDDIR: " + winddir + "\n\n";
			}
		} 
		catch (SQLException e) 
		{
			e.printStackTrace();
		}
		
		Connect.close();
		
		return output;
	}
}
